﻿using System.Collections.Generic;
using System.Linq;

namespace Basmus.ReadWrite
{
    public class ElementsReaderWriter<TValue> : IElementsReaderWriter<TValue>
    {
        private readonly IReaderWriter<TValue> _readerWriter;

        public ElementsReaderWriter(IReaderWriter<TValue> readerWriter)
        {
            _readerWriter = readerWriter;
        }

        public IEnumerable<string> Write(IEnumerable<TValue> elements)
        {
            if (elements != null)
            {
                var strings = elements
                    .Select(x => _readerWriter.Write(x));
                return strings;
            }
            return null;
        }

        public IEnumerable<TValue> Read(IEnumerable<string> strings)
        {
            if (strings != null)
            {
                var values = strings
                    .Select(x => _readerWriter.Read(x))
                    .Where(x => x.Successful)
                    .Select(x => x.Value);
                return values;
            }
            return null;
        }
    }
}